<template>
  <div class="my-await-work-wrap">
    <a-tabs v-model:active-key="searchVal.type" @change="changeStatus">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key" :title="tab.title" />
    </a-tabs>
    <div class="my-await-work-con table-gl-w">
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :isSearch="true" :isReset="false" @search="searchByVal" />
      </div>
      <div class="my-await-work table-gl-con" v-if="listData.length">
        <div class="left">
          <a-scrollbar style="height: 100%; overflow: auto; margin-top: 10px">
            <ul>
              <li v-for="(item, i) in listData" :key="i" :class="{ active: currentId == item.id }" class="flex-c-sb" @click="getDetail(item)">
                <div>
                  <div class="flex-c">
                    <div class="icon-w">{{ ShortNameMap[item.approvalType] || (item.approvalName && item.approvalName.substring(0, 2)) }}</div>
                    <div>
                      <p class="title">
                        <i class="icon icon-biaoqian"></i>
                        <span>{{ item.approvalName }}</span>
                      </p>
                      <p>
                        <span>单据号：</span>
                        <span class="highlight">{{ item.billNo }}</span>
                        <span style="margin-left: 12px">发起人：{{ item.promoterName }}</span>
                      </p>
                    </div>
                  </div>
                  <p class="time">发起时间：{{ $setTime(item.approvalTime) }}</p>
                </div>
                <a-tag color="arcoblue">{{ BillAuditStatus[item.status] }}</a-tag>
              </li>
            </ul>
          </a-scrollbar>
          <div class="pagination-footer">
            <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
          </div>
        </div>
        <div class="right">
          <template v-if="componentName && componentList[componentName]">
            <component :is="componentList[componentName]" :id="currentId" :approvalType="currentDetail.approvalType" :type="searchVal.type" @updateStatus="getTableList()" />
          </template>
          <a-empty v-else>该审批流正在开发区中...</a-empty>
        </div>
      </div>
      <a-empty v-else />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import PurchasePlanAuth from './components/purchasePlanAuth.vue'
  import PurchaseOrderAuth from './components/purchaseOrderAuth.vue'
  import OtherOutAndInAuth from './components/otherOutAndInAuth.vue'
  import TransferAuth from './components/transferAuth.vue'
  import SupplierProductAuth from './components/SupplierProductAuth.vue'
  import { findApprovalProcessConfig, findApprovalProcessPage } from '@/api/workFlow'
  import { BillAuditStatus, ShortNameMap, ComponentNameMap } from '@/views/workFlow/types'
  import { cloneDeep } from 'lodash-es'

  onMounted(() => {
    getTableList()
    getFlowList()
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'select',
      key: 'approvalType',
      label: '审批单据',
      value: ref(),
      width: 140,
      optionItems: [],
    },
    {
      type: 'select',
      key: 'status',
      label: '状态',
      value: ref(),
      width: 100,
      optionItems: Object.keys(BillAuditStatus).map((key: any) => {
        return {
          value: key,
          label: BillAuditStatus[key],
        }
      }),
    },
    {
      type: 'date_range',
      key: 'approvalTime',
      value: ref(),
      placeholder: '请输入',
      label: '发起时间',
      width: 240,
      attrs: {
        placeholder: ['发起开始日期', '发起结束日期'],
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const listData = ref<Array<any>>([])
  const tabsList = [
    { key: 1, title: '已发起' },
    { key: 2, title: '待处理' },
    { key: 3, title: '已处理' },
    { key: 4, title: '抄送我' },
  ]

  const componentName = ref('PurchasePlanAuth')
  // 组件注册（伪注册）
  const componentList = {
    PurchasePlanAuth,
    PurchaseOrderAuth,
    OtherOutAndInAuth,
    TransferAuth,
    SupplierProductAuth,
  }
  const currentDetail = ref<any>({})
  const currentId = ref()
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    type: 2,
  })
  const filterData = ref<any>({})
  const total = ref(0)

  // 获取流程列表
  async function getFlowList() {
    const res: any = await findApprovalProcessConfig()
    let list = res?.data || []
    filterItem.value[0].optionItems = list.map((el: any) => {
      return {
        value: el.approvalType,
        label: el.approvalName,
      }
    })
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.type = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 获取列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...cloneDeep(filterData.value),
    }
    if (params.approvalTime) {
      params.dataType = 'approvalTime'
      params.startDate = params.approvalTime[0]
      params.endDate = params.approvalTime[1]
    }
    delete params.approvalTime
    const res: any = await findApprovalProcessPage(params)
    listData.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    if (listData.value.length) {
      getDetail(listData.value[0])
    }
  }
  // 获取详情
  async function getDetail(row: any) {
    // if (currentId.value == row.id) return
    currentId.value = row.id
    currentDetail.value = row
    componentName.value = ComponentNameMap[currentDetail.value.approvalType]
  }
</script>

<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }

  .my-await-work-con {
    height: calc(100vh - @menuAndTabHeight);
  }
  .my-await-work {
    flex: 1;
    display: flex;
    flex-direction: row;
    background-color: transparent;
  }
  .left {
    width: 400px;
    height: 100%;
    display: flex;
    flex-shrink: 0;
    flex-direction: column;
    overflow-y: hidden;
    background-color: #fff;
    .arco-scrollbar {
      flex: 1;
      height: 100%;
      overflow-y: hidden;
    }
    ul {
      padding: 0 10px;
      li {
        border-bottom: 1px solid #eee;
        padding: 15px 10px;
        font-size: 12px;
        .icon-w {
          width: 50px;
          height: 50px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: rgb(var(--primary-5));
          border-radius: 10px;
          color: #fff;
          text-align: center;
          font-size: 14px;
          margin-right: 10px;
          padding: 4px 5px;
        }
        .icon-biaoqian {
          color: #999;
          margin-right: 5px;
        }
        .title {
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        .time {
          color: #999;
          margin-top: 10px;
          font-size: 12px;
        }
        &.active {
          background-color: #f5f5f5;
        }
      }
    }
  }
  .right {
    flex: 1;
    margin-left: 10px;
    background-color: #fff;
    height: 100%;
    overflow-x: hidden;
  }
</style>
<style scoped>
  @media screen and (max-width: 1500px) {
    .my-await-work .left {
      width: 380px !important;
    }
    .my-await-work .icon-w {
      width: 45px !important;
      height: 45px !important;
    }
  }
</style>
